import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {ParamConfig} from '../common/param.config';
import 'rxjs/add/operator/toPromise';
import {AddPlacePage, AddPlace} from './place';
import {Router} from '@angular/router';
import {UserService} from '../user/user.service';
import {AddEvent} from '../event/event';

@Injectable()
export class AddPlaceService {
  public token: string;
  private hostUrl = ParamConfig.HTTP_WEB_HOST_URL + 'place/getPlaceData'; // 查询place
  private hostUrlAddPlace = ParamConfig.HTTP_WEB_HOST_URL + 'place/savePlace'; // 新增场景
  private hostUrlDeletePlace = ParamConfig.HTTP_WEB_HOST_URL + 'place/deletePlace'; // 删除场景
  private hostUrlUpdatePlace = ParamConfig.HTTP_WEB_HOST_URL + 'place/updatePlaceWithManyEvent'; // 更新场景
  private hostUrlEvent = ParamConfig.HTTP_WEB_HOST_URL + 'event/getWebEventData'; // 查询事件
  private hostUrlPlace = ParamConfig.HTTP_WEB_HOST_URL + 'place/getPlaceById'; // 根据场景id获取场景
  constructor(private http: Http, private userService: UserService, private router: Router) {
  };

// 查询场景
  getPlace(page): Promise<any> {
    const request = JSON.stringify({
      rows: ParamConfig.DATA_LIST_PAGE_SIZE,
      page: page,
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrl, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            const pagedata = new AddPlacePage();
            pagedata.addPlace = body as AddPlace[];
            pagedata.totalPages = body.total;
            return pagedata;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 查询场景
  getPlaceEvent(id): Promise<any> {
    const request = JSON.stringify({
      placeId: id
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlPlace, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return [true, body.placeInfo];
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 查询事件
  getEv(page): Promise<any> {
    const request = JSON.stringify({
      rows: ParamConfig.DATA_LIST_PAGE_SIZE,
      page: 1000,
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlEvent, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            const pagedata = new AddPlacePage();
            pagedata.addEvent = body as AddEvent[];
            pagedata.totalPages = body.total;
            return pagedata;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 增加场景
  addPlaceinfo(addPlace: AddPlace, fileId, strEvent): Promise<any> {
    const request = JSON.stringify({
      name: addPlace.name,
      eventIds: strEvent,
      fileId: fileId
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlAddPlace, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 修改场景
  updatePlaceinfo(strEvent, addPlace: AddPlace, fileId): Promise<any> {
    const request = JSON.stringify({
      placeId: addPlace.id,
      name: addPlace.name,
      eventIds: strEvent,
      fileId: fileId
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlUpdatePlace, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 1) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

// 删除场景
  removeEventinfo(addPlace: AddPlace): Promise<any> {
    const request = JSON.stringify({
      placeId: addPlace.id
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlDeletePlace, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<[boolean, any]> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject([false, error.toString()]);
  }
}
